package com.fandou.paiti.topic

import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import androidx.fragment.app.Fragment
import com.abcpen.model.AnswerModel
import com.blankj.utilcode.util.LogUtils
import com.fandou.paiti.R
import com.google.gson.Gson
import kotlinx.android.synthetic.main.topic_result_fragment.*
import org.jsoup.Jsoup
import org.jsoup.nodes.Document

/**
 * @author       Jm
 * @date         2020/6/2216:14
 * @description  the result fragment
 */
class TopicResultFragment : Fragment() {

    private var mData: AnswerModel? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.topic_result_fragment, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mData = requireArguments().getParcelable("data")
        LogUtils.dTag("TopicResultFragment", Gson().toJson(mData))
        LogUtils.dTag("TopicResultFragment", "question_html:" + mData!!.question_html)
        LogUtils.dTag("TopicResultFragment", "quesiton_answer:" + mData!!.quesiton_answer)
        loadHtml(web_question, getQuestionHtml())
        loadHtml(web_answer, getAnswers())
        loadHtml(web_knowledge_point, getknowledgePoint())
    }

    private fun loadHtml(view: WebView, html: String) {
        view.loadData(html, "text/html", "utf-8")
    }

    /**
     * get the question content after converted
     */
    private fun getQuestionHtml(): String {
        return convertHtml(mData!!.question_html).html()
    }


    /**
     * get the answers content after converted
     */
    private fun getAnswers(): String {

        val source = mData!!.quesiton_answer
        if (TextUtils.isEmpty(source)) {
            return "暂无"
        } else {
            return convertHtml(source).html()
        }
    }

    /**
     * get the knowledge point content after converted
     * 知识点分析返回的数据可能存在 “”，字符串的NULL,"暂无"等情况。尚未明确更多情况。
     * 这里暂时统一处理为“暂无”
     */
    private fun getknowledgePoint(): String {
        val source = mData!!.answer_analysis
        if (source == "NULL" || source == "暂无" || !TextUtils.isEmpty(source)) {
            return "暂无"
        } else {
            return convertHtml(source).html()
        }
    }


    /**
     * 1.经实践采取替换这些转义后的标签最为稳妥，如果使用如下方法，会有几率出现异常.
     * val engineByExtension = ScriptEngineManager().getEngineByExtension("js")
     * var targetHtml = ""
     * try {
     *   targetHtml = engineByExtension.eval("unescape('$HTML4')").toString()
     * } catch (e: ScriptException) {
     *     e.printStackTrace()
     * }
     *
     * 2.部分返回来的html的图片变迁被添加了一个alt的东西，导致无法正常解析到图片地址，所以替换掉。
     */
    private fun convertHtml(html: String): Document {
        var targetData = ""
        LogUtils.dTag("getHtml", "before convert-------------------" + html)
        targetData = html.replace("/\\\\u([0-9a-f]{3,4})/i", "&#x\\1;").replace("alt", "")
        LogUtils.dTag("getHtml", "after convert-------------------" + targetData)
        val doc = Jsoup.parse(targetData) as Document
        val table = doc.select("table")
        table?.forEach {
            table.removeAttr("width")
            table.attr("width", "100%")
        }
        return doc
    }


    companion object {
        /**
         * @param answer AnswerModel
         */
        @JvmStatic
        fun newInstance(answer: AnswerModel?): TopicResultFragment {
            return TopicResultFragment().also { fragment ->
                fragment.arguments = Bundle().also {
                    it.putParcelable("data", answer)
                }
            }
        }
    }
}